package cn.edu.ecut.se2024.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;

import cn.edu.ecut.se2024.exception.UnauthorizedException;
import cn.edu.ecut.se2024.model.UserMenu;
import cn.edu.ecut.se2024.service.SysService;
import jakarta.servlet.http.HttpServletRequest;

@ControllerAdvice(assignableTypes=AuthorizedController.class)
@Controller
public class AuthorizedController {
	public static final String SYS_USER_MENU = "sys.UserMenu";
	public static final String SYS_JSP_URL = "sys.JspURL";
	public static final String SYS_MAIN_PAGE = "main";
	public static final String SYS_LOGIN_FAILED = "sys.loginFailed";
	
	@Autowired
	private SysService sysService;
	
	@ModelAttribute()
	public void setJspUrl(HttpServletRequest request)  throws UnauthorizedException {
		UserMenu userMenu = (UserMenu)request.getSession().getAttribute(SYS_USER_MENU);
		String jspCode = request.getRequestURI().substring(1);
		String jspURL = sysService.getJspUrl(jspCode, userMenu);
		if (jspURL == null) {
			throw new UnauthorizedException();
		} else {
			//System.out.println(jspCode + "->" + jspURL);
			request.setAttribute(SYS_JSP_URL, jspURL + ".jsp");
		}
    }
	
	@ExceptionHandler(Exception.class)
	public String serveAllException(HttpServletRequest request, Exception ex) {
		request.setAttribute(SYS_JSP_URL, "error.jsp");
		return SYS_MAIN_PAGE;
    }
}
